const University = require('../models/University');

// 获取所有高校
const getAllUniversities = async (req, res) => {
  try {
    const { page = 1, limit = 10, search, location, isCentral, governingDepartment } = req.query;
    
    // 构建查询条件
    const query = {};
    if (search) {
      query.$or = [
        { schoolName: { $regex: search, $options: 'i' } },
        { contactName: { $regex: search, $options: 'i' } },
        { contactDepartment: { $regex: search, $options: 'i' } }
      ];
    }
    if (location) query.location = location;
    if (isCentral !== undefined) query.isCentral = isCentral === 'true';
    if (governingDepartment) query.governingDepartment = governingDepartment;

    // 处理排序
    let sortObj = { createdAt: -1 }; // 默认排序
    if (req.query.sortBy && req.query.sortOrder) {
        const sortBy = req.query.sortBy;
        const sortOrder = req.query.sortOrder === 'asc' ? 1 : -1;
        sortObj = { [sortBy]: sortOrder };
    }

    const universities = await University.find(query)
      .populate('planCount')
      .sort(sortObj)
      .limit(limit * 1)
      .skip((page - 1) * limit);

    const total = await University.countDocuments(query);

    res.json({
      data: {
        universities,
        totalPages: Math.ceil(total / limit),
        currentPage: parseInt(page),
        total
      },
      message: '获取高校列表成功'
    });
  } catch (error) {
    res.status(500).json({ error: '获取高校列表失败', message: error.message });
  }
};

// 根据ID获取高校
const getUniversityById = async (req, res) => {
  try {
    const university = await University.findById(req.params.id).populate('planCount');
    
    if (!university) {
      return res.status(404).json({ error: '高校不存在' });
    }
    
    res.json({
      data: university,
      message: '获取高校信息成功'
    });
  } catch (error) {
    res.status(500).json({ error: '获取高校信息失败', message: error.message });
  }
};

// 创建高校
const createUniversity = async (req, res) => {
  try {
    const university = new University(req.body);
    await university.save();
    
    res.status(201).json({
      data: university,
      message: '创建高校成功'
    });
  } catch (error) {
    if (error.name === 'ValidationError') {
      return res.status(400).json({ error: '数据验证失败', message: error.message });
    }
    if (error.code === 11000) {
      const field = Object.keys(error.keyPattern)[0];
      return res.status(400).json({ 
        error: `${field === 'schoolName' ? '学校名称' : '学校标准码'}已存在` 
      });
    }
    res.status(500).json({ error: '创建高校失败', message: error.message });
  }
};

// 更新高校
const updateUniversity = async (req, res) => {
  try {
    const university = await University.findByIdAndUpdate(
      req.params.id,
      req.body,
      { new: true, runValidators: true }
    );
    
    if (!university) {
      return res.status(404).json({ error: '高校不存在' });
    }
    
    res.json({
      data: university,
      message: '更新高校成功'
    });
  } catch (error) {
    if (error.name === 'ValidationError') {
      return res.status(400).json({ error: '数据验证失败', message: error.message });
    }
    if (error.code === 11000) {
      const field = Object.keys(error.keyPattern)[0];
      return res.status(400).json({ 
        error: `${field === 'schoolName' ? '学校名称' : '学校标准码'}已存在` 
      });
    }
    res.status(500).json({ error: '更新高校失败', message: error.message });
  }
};

// 删除高校
const deleteUniversity = async (req, res) => {
  try {
    // 检查是否有关联的授课计划
    const Plan = require('../models/Plan');
    const planCount = await Plan.countDocuments({ universityId: req.params.id });
    
    if (planCount > 0) {
      return res.status(400).json({ error: '该高校还有授课计划，无法删除' });
    }

    // 检查是否有干部将此高校设为意向高校
    const Cadre = require('../models/Cadre');
    const cadreCount = await Cadre.countDocuments({
      $or: [
        { intendedUniversity1: req.params.id },
        { intendedUniversity2: req.params.id },
        { intendedUniversity3: req.params.id }
      ]
    });

    if (cadreCount > 0) {
      return res.status(400).json({ error: '该高校被干部设为意向高校，无法删除' });
    }

    const university = await University.findByIdAndDelete(req.params.id);
    
    if (!university) {
      return res.status(404).json({ error: '高校不存在' });
    }
    
    res.json({ message: '高校删除成功' });
  } catch (error) {
    res.status(500).json({ error: '删除高校失败', message: error.message });
  }
};

// 获取高校选项（用于下拉选择）
const getUniversityOptions = async (req, res) => {
  try {
    const universities = await University.find({}, 'schoolName location isCentral').sort({ schoolName: 1 });
    res.json({
      data: universities,
      message: '获取高校选项成功'
    });
  } catch (error) {
    res.status(500).json({ error: '获取高校选项失败', message: error.message });
  }
};

module.exports = {
  getAllUniversities,
  getUniversityById,
  createUniversity,
  updateUniversity,
  deleteUniversity,
  getUniversityOptions
};
